package dhu.cst.jnlwt.jiangnan181310209liwanting181310302.tally.fragment_bill;

import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.graphics.Color;
import android.os.Bundle;

import androidx.fragment.app.Fragment;

import android.provider.ContactsContract;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;

import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.components.Description;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.formatter.IndexAxisValueFormatter;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Random;

import dhu.cst.jnlwt.jiangnan181310209liwanting181310302.tally.R;
import dhu.cst.jnlwt.jiangnan181310209liwanting181310302.tally.activity_tally.HomeActivity;
import dhu.cst.jnlwt.jiangnan181310209liwanting181310302.tally.adapter.TrendAdapter;
import dhu.cst.jnlwt.jiangnan181310209liwanting181310302.tally.database.AccountDao;
import dhu.cst.jnlwt.jiangnan181310209liwanting181310302.tally.database.DatabaseHelper;
import dhu.cst.jnlwt.jiangnan181310209liwanting181310302.tally.entity.AccountBean;
import dhu.cst.jnlwt.jiangnan181310209liwanting181310302.tally.entity.TrendBean;


public class TrendFragment extends Fragment {

    private String phoneNumber;//用户手机号
    private LineChart lineChart;//折线图控件
    private ListView listView;//列表控件
    private ImageButton btn_leftArrow;//左箭头控件
    private ImageButton btn_rightArrow;//右箭头控件
    private ImageButton back;
    private TextView textView_year;//年份显示控件
    private int year;//年份

    private ArrayList<TrendBean> msgList;//列表所需信息
    private TrendAdapter mAdapter;//适配器

    private ArrayList<Entry> entries1 = new ArrayList<>();//支出纵坐标值
    private ArrayList<Entry> entries2 = new ArrayList<>();//收入纵坐标值
    private ArrayList<String> xValues = new ArrayList<>();//横坐标值

    AccountDao dbManager;//账单查询

    public TrendFragment() {

    }


    public TrendFragment(String phoneNumber) {
        this.phoneNumber=phoneNumber;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_trend,container,false);
        lineChart = view.findViewById(R.id.lineChart_trend);
        listView = view.findViewById(R.id.listView_trend);
        btn_leftArrow = view.findViewById(R.id.btn_leftArrow);
        btn_rightArrow = view.findViewById(R.id.btn_rightArrow);
        back = view.findViewById(R.id.trend_back);
        textView_year = view.findViewById(R.id.textView_year);
        msgList = new ArrayList<>();
        mAdapter = new TrendAdapter(msgList,this.getContext());
        listView.setAdapter(mAdapter);
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getActivity().finish();
            }
        });

        //默认年份为当前年份
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
        String date = sdf.format(new Date());
        textView_year.setText(date);
        year = Integer.parseInt(date);

        btn_leftArrow.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                textView_year.setText(Integer.toString(year-1));
                year = year-1;
                entries1.clear();
                entries2.clear();
                msgList.clear();

                getData();
                mAdapter.notifyDataSetChanged();
            }
        });

        btn_rightArrow.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                textView_year.setText(Integer.toString(year+1));
                year = year+1;
                entries1.clear();
                entries2.clear();
                msgList.clear();

                getData();
                mAdapter.notifyDataSetChanged();
            }
        });
        dbManager = new AccountDao(getContext(),phoneNumber);
        getData();
        return view;
    }

    private void setLine(){
        for(int i = 1; i < 13; i++){
            xValues.add(Integer.toString(i));
        }
        setLineStyle();
        setXYStyle();
        hide();
        setData();

        MyMarkerView mv = new MyMarkerView(this.getContext(),R.layout.textview_marker,lineChart,xValues);
        mv.setChartView(lineChart);
        lineChart.setMarker(mv);
        initMessage();
    }

    //设置线条样式
    private void setLineStyle(){
        LineDataSet dataSet1 = new LineDataSet(entries1,"Label");
        dataSet1.setColor(Color.parseColor("#7d7d7d"));//线条颜色
        dataSet1.setCircleColor(Color.parseColor("#22B14C"));//圆点颜色
        dataSet1.setLineWidth(3f);//线条宽度

        LineDataSet dataSet2 = new LineDataSet(entries2,"Label");
        dataSet2.setColor(Color.parseColor("#00A2E8"));//线条颜色
        dataSet2.setCircleColor(Color.parseColor("#7d7d7d"));//圆点颜色
        dataSet2.setLineWidth(3f);//线条宽度
    }
    //设置XY轴样式
    private void setXYStyle() {
        YAxis rightAxis = lineChart.getAxisRight();
        YAxis leftAxis = lineChart.getAxisLeft();
        //设置图表右边的y轴禁用
        rightAxis.setEnabled(false);
        //设置网格线为虚线效果
        leftAxis.enableGridDashedLine(10f, 10f, 0f);
        //设置x轴
        XAxis xAxis = lineChart.getXAxis();
        xAxis.setTextColor(Color.parseColor("#333333"));
        xAxis.setTextSize(11f);
        xAxis.setAxisMinimum(0f);
        xAxis.setLabelCount(12);
        xAxis.setDrawAxisLine(true);//是否绘制轴线
        xAxis.setDrawGridLines(false);//设置x轴上每个点对应的线
        xAxis.setDrawLabels(true);//绘制标签  指x轴上的对应数值
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);//设置x轴的显示位置
        xAxis.setGranularity(1f);//禁止放大后x轴标签重绘

        xAxis.setValueFormatter(new IndexAxisValueFormatter(xValues));
    }
    //隐藏图例和描述
    private void hide() {

        //隐藏图例
        Legend legend = lineChart.getLegend();
        legend.setForm(Legend.LegendForm.NONE);
        legend.setTextColor(Color.WHITE);

        //隐藏x轴描述
        Description description = new Description();
        description.setEnabled(false);
        lineChart.setDescription(description);
    }

    //填充数据
    private void setData() {

        //把数据赋值到你的线条
        LineDataSet dataSet1 = new LineDataSet(entries1, "Label");
        LineDataSet dataSet2 = new LineDataSet(entries2, "Label");
        //chart设置数据
        LineData data = new LineData(dataSet1,dataSet2);
        //是否绘制线条上的文字
        data.setDrawValues(false);
        lineChart.setData(data);
        lineChart.invalidate();
    }

    private void getData(){
        for(int i = 1; i <= 12; i++){
            String month;
            if(i<10){month="0"+i;}
            else{month=""+i;}
            List<AccountBean> expenditureList = dbManager.getExpenditureList(textView_year.getText().toString()+"."+month);
            double expenditureSum = 0;
            for(int j = 0; j < expenditureList.size();j++){
                expenditureSum += expenditureList.get(j).getAccount();
            }
            entries1.add(new Entry(i-1,(float) expenditureSum));
            List<AccountBean> incomeList = dbManager.getIncomeList(textView_year.getText().toString()+"."+month);
            double incomeSum = 0;
            for(int j = 0; j < incomeList.size();j++){
                incomeSum += incomeList.get(j).getAccount();
            }
            entries2.add(new Entry(i-1,(float) incomeSum));

        }
        setLine();
    }

    //listview获取数据
    private void initMessage() {
        TrendBean monthAccount = new TrendBean("时间","支出","收入");
        msgList.add(monthAccount);

        LineData lineData=lineChart.getLineData();//得到已经绘制成型的折线图的数据
        LineDataSet set1=(LineDataSet)lineData.getDataSetByIndex(0);//获取第一条折线图Y轴数据
        LineDataSet set2=(LineDataSet)lineData.getDataSetByIndex(1);//获取第二条折线图Y轴数据
        for(int index=0;index<12;index++) {
            //根据index值，分别获取当前X轴上对应的两条折线的Y轴的值
            Entry entry1 = set1.getEntryForIndex(index);
            Entry entry2 = set2.getEntryForIndex(index);
            monthAccount = new TrendBean(index+1+ "月\n",new DecimalFormat("0.00").format(entry1.getY()) ,new DecimalFormat("0.00").format(entry2.getY()));
            msgList.add(monthAccount);
        }
    }
}